<?php
namespace traits;
use swift\Response;
use swift\response\Redirect;

trait Jump{
    /**
     * URL重定向
     * @access protected
     * @param string         $url 跳转的URL表达式
     * @param array          $params 其它URL参数
     * @param integer        $code http code
     * @return void
     */
    protected function redirect($url , $params = [] , $code = 302){
        $response = new Redirect($url);
        $response->code($code)->params($params);
        return $response;
    }

    /**
     * 返回封装后的API数据到客户端
     * @access protected
     * @param mixed     $data 要返回的数据
     * @param integer   $code 返回的code
     * @param array     $header 发送的Header信息
     * @param string    $type 返回数据格式
     * @return void
     */
    protected function result($data , $code = 200 , array $header = [] , $type = 'json'){
        $result = [
            'code' => $code,
            'time' => $_SERVER['REQUEST_TIME'],
            'result' => $data,
        ];
        return Response::create($result , $type)->header($header);
    }

    /**
     * json返回
     * @param mixed     $data 要返回的数据
     * @param array     $header 发送的Header信息
     */
    protected function json($data ,array $header = [] ){
        return Response::create($data , 'json')->header($header);
    }

    protected function ajaxReturn($data , array $header = [] ){
        return Response::create($data , 'json')->header($header);
    }

    protected function ajaxSuccess($data , array $header = [] ){
        $result['content'] = $data;
        $result['error'] = 0;
        $result['message'] = "";
        return Response::create($result , 'json')->header($header);
    }

    protected function ajaxError($data , array $header = [] ){
        $result['content'] = "";
        $result['error'] = 1;
        $result['message'] = $data;
        return Response::create($result , 'json')->header($header);
    }
}
